package com.extra;

import java.util.LinkedList;

public class Solution116 {
    public Node connect(Node root) {
        connectNode(root);
        return root;
    }

    public void connectNode(Node root) {
        if (root == null) return;
        if (root.left != null) {
            root.left.next = root.right;
        }
        if (root.right != null) {
            if (root.next != null) {
                root.right.next = root.next.left;
            } else root.right.next = null;
        }
        connectNode(root.left);
        connectNode(root.right);
    }

    public Node connect2(Node root) {
        if (root == null) return null;
        LinkedList<Node> list = new LinkedList<>();
        list.add(root);
        while (!list.isEmpty()) {
            int size = list.size();
            int i = 0;
            Node pre = null;
            while (size-- > 0) {
                Node tmp = list.removeFirst();
                if (i == 0) {
                    pre = tmp;
                    i++;
                } else {
                    pre.next = tmp;
                    pre = tmp;
                }
                if (tmp.left != null) list.add(tmp.left);
                if (tmp.right != null) list.add(tmp.right);
            }
        }
        return root;
    }
}

class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {
    }

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
}
